package com.fywsy.fyweb.strategy;

import com.fywsy.fyweb.entity.SendItem;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

@Component
public class GameStrategyFactory {

    private final ApplicationContext applicationContext;

    public GameStrategyFactory(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public String executeStrategy(long gameId, long gongnengId, SendItem sendItem) {
        // 获取所有的策略类实例
        Map<String, BaseGameStrategy> strategies = applicationContext.getBeansOfType(BaseGameStrategy.class);

        // 通过反射查找与gameId匹配的策略类
        for (Object strategy : strategies.values()) {
            // 获取策略类的 @GameId 注解
            GameId gameIdAnnotation = strategy.getClass().getAnnotation(GameId.class);
            if (gameIdAnnotation != null && gameIdAnnotation.value() == gameId) {
                // 如果 gameId 匹配，查找该策略类中的方法
                for (Method method : strategy.getClass().getMethods()) {
                    // 查找方法上的 @GongnengMethod 注解
                    GongnengMethod gongnengMethodAnnotation = method.getAnnotation(GongnengMethod.class);
                    if (gongnengMethodAnnotation != null && gongnengMethodAnnotation.value() == gongnengId) {
                        try {
                            // 调用方法，并获取执行结果
                            Object result = method.invoke(strategy, sendItem);
                            if (result != null) {
                                return (String) result;
                            } else {
                                return "执行成功，未返回结果";
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            return "执行失败：" + e.getMessage();
                        }
                    }
                }
            }
        }
        return "开发中！请等待";
    }
}
